import 'package:flutter/material.dart';
import 'package:flutter_wisave/widgets/AppColors.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wisave/eye/EyeItem.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import '../../Tools/ToolsLocalStorage.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage>
    with SingleTickerProviderStateMixin {
  bool breakdown = true; // Add this line
  final NetworkService _networkService = NetworkService();
  List<dynamic> listData = [];
  List<dynamic> noListData = [];
  List<dynamic> allListData = [];
  var childDeptName = '';

  //生命周期函数：当组件初始化的时候就会触发
  //输入inits可快速生成该方法
  @override
  void initState() {
    super.initState();
    _loadData();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _loadData();
  }

  Future<void> _loadData() async {
    childDeptName = (await LocalStorage.getstr('childDeptName'))!;
    try {
      final result = await _fetchData();
      if (result['code'] == 200 && result['rows'] != null) {
        setState(() {
          allListData = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
          listData =
              allListData.where((item) => item['isFavorited'] == 1).toList();
          noListData =
              allListData.where((item) => item['isFavorited'] == 0).toList();
          print('SearchPage-Date: ${result}');
        });
      } else {
        print('Error: ${result['msg']}');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService
          .get('/plcTimer/monitor/selecList?companyId=$deptID');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('steeloutday Failed to load data');
      }
    } catch (e) {
      print('steeloutday Error in _fetchData: $e');
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 状态栏颜色
    ));

    final mediaQuery = MediaQuery.of(context);
    final screenWidth = mediaQuery.size.width;
    final screenHeight = mediaQuery.size.height;

    return Scaffold(
      backgroundColor: AppColors.backgroundColor,
      appBar: AppBar(
        // title: const Text('云眼'),
        centerTitle: true,
        backgroundColor: Colors.transparent, // 使 AppBar 透明
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home/home_topbg.png'),
              fit: BoxFit.fill,
            ),
          ),
        ),
        actions: [
          const SizedBox(width: 10),
          GestureDetector(
            onTap: () {},
            child: Image(
              image: AssetImage(AppColors.isDarkMode
                  ? 'assets/images/home/nav_logo_d.png'
                  : 'assets/images/home/nav_logo.png'),
              width: 76,
              height: 76,
            ),
          ),
          const SizedBox(width: 10), // 添加间隔
          Flexible(
            child: Center(
              child: TDText(
                '云眼',
                maxLines: 1, // 限制为单行显示
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: AppColors.textPrimary,
                  fontWeight: FontWeight.w500,
                  fontSize: 20,
                ),
              ),
            ),
          ),
          TDButton(
            text: childDeptName.length > 10
                ? childDeptName.substring(0, 10) + '...'
                : childDeptName,
            size: TDButtonSize.small,
            // width: 140,
            style: TDButtonStyle(
              backgroundColor: Colors.transparent,
            ),
            textStyle: TextStyle(
              color: AppColors.textPrimary,
              fontWeight: FontWeight.w300,
            ),
            onTap: () {
              // 在这里添加按钮点击事件的处理逻辑
            },
          ),
        ],
      ),
      body: Stack(children: [
        ListView(children: [
          const SizedBox(height: 20),
          Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ..._buttonWithType('已添加云眼', screenWidth, !this.breakdown, 2,
                      () {
                    setState(() {
                      this.breakdown = false;
                      _loadData;
                    });
                  }),
                  const SizedBox(width: 10),
                  ..._buttonWithType('全部云眼', screenWidth, this.breakdown, 2,
                      () {
                    setState(() {
                      this.breakdown = true;
                      _loadData;
                    });
                  }),
                ],
              ),
              const SizedBox(height: 20),
              SingleChildScrollView(
                child: Container(
                  child: GridView.builder(
                    shrinkWrap: true,
                    physics:
                        const NeverScrollableScrollPhysics(), // 禁用 GridView 的滚动
                    padding: const EdgeInsets.symmetric(horizontal: 10),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      childAspectRatio:
                          MediaQuery.of(context).size.width / (2 * 200),
                      mainAxisSpacing: 1,
                      crossAxisSpacing: 10,
                    ),
                    itemCount:
                        !breakdown ? listData.length : allListData.length,
                    itemBuilder: (context, index) {
                      return EyeItem(
                        data: !breakdown ? listData[index] : allListData[index],
                        onRefresh: _loadData,
                      );
                    },
                  ),
                ),
              ),
              const SizedBox(height: 20),
              if (!breakdown)
                GestureDetector(
                  onTap: () {
                    setState(() {
                      breakdown = true;
                    });
                  },
                  child: Container(
                    width: MediaQuery.of(context).size.width - 40,
                    height: 50,
                    decoration: BoxDecoration(
                      image: const DecorationImage(
                        image: AssetImage('assets/images/login/login_bg.png'),
                        fit: BoxFit.fill,
                      ),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: const Center(
                      child: Text(
                        '添加云眼',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                        ),
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ]),
      ]),
    );
  }
}

List<Widget> _buttonWithType(String title, double screenWidth, bool select,
    int tabIndex, VoidCallback onTap) {
  String imgBg = 'assets/images/cloud/cloud_gray.png';
  String imgIcon = 'assets/images/home/icon_eye_un.png';
  if (select) {
    imgBg = AppColors.isDarkMode
        ? 'assets/images/cloud/cloud_blue_b.png'
        : 'assets/images/cloud/cloud_blue.png';
    if (title == '已添加云眼') {
      imgIcon = 'assets/images/home/icon_eye_blue.png';
    } else {
      imgIcon = 'assets/images/home/icon_eye_blue.png';
    }
  } else {
    imgBg = AppColors.isDarkMode
        ? 'assets/images/cloud/cloud_gray_b.png'
        : 'assets/images/cloud/cloud_gray.png';
    if (title == '已添加云眼') {
      imgIcon = 'assets/images/home/icon_eye_un.png';
    } else {
      imgIcon = 'assets/images/home/icon_eye_un.png';
    }
  }

  return [
    GestureDetector(
      onTap: onTap,
      child: Container(
        height: 50,
        width: (screenWidth - 50) / 2,
        decoration: BoxDecoration(
          // color: Colors.white, // Add white background
          image: DecorationImage(
            image: AssetImage(imgBg),
            fit: BoxFit.cover,
          ),
          borderRadius: BorderRadius.circular(8.0),
        ),
        child: Stack(
          children: [
            Positioned.fill(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const SizedBox(
                      width: 8), // Add some space between image and text
                  Image.asset(
                    imgIcon, // Replace with your image path
                    width: 30, // Adjust size as needed
                    height: 30,
                  ),
                  const SizedBox(
                      width: 12), // Add some space between image and text
                  Text(
                    title,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: AppColors.textPrimary,
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    ),
  ];
}
